﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using TeamOPSchoolCup.Web.Models;

namespace TeamOPSchoolCup.Web.Controllers
{
  public class AccountController : Controller
  {
    //
    // GET: /Account/LogOn

    public ActionResult LogOn()
    {
      return PartialView("LogOn",new LogOnModel());
    }

    [HttpPost]
    public ActionResult LogOn(LogOnModel model, string returnUrl)
    {
      if (ModelState.IsValid)
      {
        if (Membership.GetUser(model.Email) != null)
        {
          if (Membership.ValidateUser(model.Email, model.Password))
          {
            FormsAuthentication.SetAuthCookie(model.Email, model.RememberMe);
            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
              return Redirect(returnUrl);
            }

            return RedirectToAction("Index", "Home");
          }
          else
          {
            ModelState.AddModelError("", "The password is incorrect.");
          }
        }
        else
        {
          ModelState.AddModelError("", "This user could not be found.");
        }
      }
      return View();
    }

    public ActionResult LogOff()
    {
      FormsAuthentication.SignOut();

      return RedirectToAction("Index", "Home");
    }

    [Authorize]
    public ActionResult ChangePassword()
    {
      return View();
    }

    [Authorize]
    [HttpPost]
    public ActionResult ChangePassword(ChangePasswordModel model)
    {
      if (ModelState.IsValid)
      {
        MembershipUser user = Membership.GetUser(User.Identity.Name, true);

        if (Membership.ValidateUser(user.UserName, model.OldPassword))
        {
          if (user.ChangePassword(model.OldPassword, model.NewPassword))
          {
            return RedirectToAction("ChangePasswordSuccess");
          }
          else
          {
            ModelState.AddModelError("", "The new password is invalid.");
          }
        }
        else
        {
          ModelState.AddModelError("", "The current password is incorrect.");
        }
      }
      return View(model);
    }

    [Authorize]
    public ActionResult ChangePasswordSuccess()
    {
      return View();
    }
  }
}
